package controllers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import constants.Default;
import constants.TplPath;
import constants.session.Session;
import constants.system.GuestAuthorization;
import constants.system.MemberShip;
import constants.ws.PageBean;
import duppentity.dto.sys.SysDtoUtil;
import duppentity.dto.sys.SysItemDto;
import duppentity.dto.user.UserInfoDto;
import duppentity.dto.user.UserInfoDtoUtil;
import utils.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author yangzhi
 * @date 2018/12/5
 */
public class UserController  extends ApiController{

	/**
	 * 登陸验证码
	 */
	@GuestAuthorization
	public static void shows(){
		CaptchaHelper.create(request, response);
	}

	/**
	 * 注册手机验证码
	 */
	@GuestAuthorization
	public static void showCodes() {
		String mobile = RequestHelper.getParam("phone",0);

		if (!Utils.isMobilephone(mobile)){
			apiError("请输入正确的手机号");
		}
		JsonObject user =userDupp.getkfbkUserByMobile(mobile);
		if (user==null || user.get("total").getAsInt()==0){
			apiError("不存在此手机号");
		}
		CaptchaHelper.createCode(request, response,mobile);
	}

	/**
	 * 登陆
	 */
	@GuestAuthorization
	public static void login(){
		String path= TplPath.login;
		Integer isTop = RequestHelper.getIntParam("isTop");
		renderTemplate(path,isTop);
	}


	@GuestAuthorization
	public static void postLogin() {

		String userName = RequestHelper.getParam("username", 0);
		String passWord = RequestHelper.getParam("password", 0);
        String vercode = RequestHelper.getParam("vercode", 0);

		if (!CaptchaHelper.isCorrect(request, vercode, Default.codeType.one)) {
			apiError("输入的验证码不正确");
		}
		//登陆
		JsonObject result = userDupp.loginByPassword(userName, play.libs.Codec.hexMD5(passWord));

		if (checkResult(result)) {
			JsonObject userInfo = result.get("list").getAsJsonArray().get(0).getAsJsonObject();
			Long id = userInfo.get("id").getAsLong();
			//姓名
			String name = userInfo.get("name").getAsString();
			//服务端返回的sessionId
			String sessionId = userInfo.get("sessionId").getAsString();
			//登录用户全部角色id
			String userRoleIds = getUserRoleIds(result);
			//登录成功缓存权限
			List<SysItemDto> list=getUserItemList(result);
			if (list.size()==0){
				apiError("暂无权限，请管理员分配权限");
			}
			MemberShip.change(id, name, sessionId,userRoleIds);
			//排序
			Collections.sort(list, new Comparator<SysItemDto>() {
				@Override
				public int compare(SysItemDto o1, SysItemDto o2) {
					return o1.sequence.compareTo(o2.sequence);
				}
			});

			Session itemSession=Session.current();
			String userKey =  id.toString().concat("_userItemList");
			if (itemSession.get(userKey)!=null){
				//删除旧权限
				itemSession.remove(userKey);
				//更新最新权限
				itemSession.add(userKey,list);
			}else{
				//没有直接缓存权限
				itemSession.add(userKey,list);
			}

			apiOk("登陆成功");
		} else {
			apiError(result);
		}
	}

	/**
	 * 登录用户全部角色ids
	 * @param data
	 * @return
	 */
	private static String getUserRoleIds(JsonObject data){
		StringBuilder sb = new StringBuilder();
		JsonObject userInfo = data.get("list").getAsJsonArray().get(0).getAsJsonObject();
		//sysAdminRoleIds===>>sys_admin_role
		JsonArray jsonArray =userInfo.getAsJsonArray("sysAdminRoleIds");
		if (jsonArray!=null && jsonArray.size()>0) {
			for (Integer i = 0; i < jsonArray.size(); i++) {
				Long id = jsonArray.get(i).getAsLong();
				JSONObject sysAdminRole = JSONObjectUtils.get(data, "sys_admin_role");
				Long roleId = JSONObjectUtils.getLong(sysAdminRole, id.toString(), "roleId");
				if (i==jsonArray.size()-1){
					sb.append(roleId);
				}else {
					sb.append(roleId).append(",");
				}
			}
		}
		return  sb.toString();
	}

	/**
	 * 登录后获取当前用户权限列表
	 * @param data
	 * @return
	 */
	private static List<SysItemDto> getUserItemList(JsonObject data){
		List<SysItemDto> sysItemDtoList = new ArrayList<>();
		JsonObject userInfo = data.get("list").getAsJsonArray().get(0).getAsJsonObject();
		//sysAdminRoleIds===>>sys_admin_role
		JsonArray jsonArray =userInfo.getAsJsonArray("sysAdminRoleIds");
		List<Long> resultItemId = new ArrayList<>();
		if (jsonArray!=null && jsonArray.size()>0){
			for (Integer i=0;i<jsonArray.size();i++){
				Long id = jsonArray.get(i).getAsLong();
				JSONObject sysAdminRole = JSONObjectUtils.get(data, "sys_admin_role");
				Long roleId = JSONObjectUtils.getLong(sysAdminRole, id.toString(), "roleId");

				if (roleId>0) {
					JSONObject sysRole = JSONObjectUtils.get(data, "sys_role");
					JSONArray sysRoleItemIds =JSONObjectUtils.getJSONObject(sysRole,roleId.toString()).getJSONArray("sysRoleItemIds");
					if(sysRoleItemIds.size()>0) {
						for (Integer j = 0; j<sysRoleItemIds.size(); j++) {
							Long roleItemId = sysRoleItemIds.getLong(j);

							JSONObject sysRoleItem = JSONObjectUtils.get(data, "sys_role_item");
							Long itemId = JSONObjectUtils.getLong(sysRoleItem, roleItemId.toString(), "itemId");
							resultItemId.add(itemId);

							JSONObject sysItem = JSONObjectUtils.get(data, "sys_item");
							JSONObject item = JSONObjectUtils.getJSONObject(sysItem, itemId.toString());

							sysItemDtoList.add(SysDtoUtil.convertSysItemDto(item));
						}
					}
				}
			}
		}
		return  sysItemDtoList;
	}

	public static void updatePwd(){
		String path= TplPath.updatePwd;
		MemberShip memberShip = MemberShip.current();
		String name = memberShip.getName();
		renderTemplate(path,name);
	}

	public static void updatePassword(){
		MemberShip memberShip = MemberShip.current();

		String oldPwd = RequestHelper.getParam("oldPassword", 0);
		String newPwd = RequestHelper.getParam("password", 0);

		//管理员修改密码
		JsonObject	data =	userDupp.updatePassword(memberShip.getId(), play.libs.Codec.hexMD5(oldPwd), play.libs.Codec.hexMD5(newPwd), memberShip.getId());

		if (checkResult(data)) {
			if(data.get("result").getAsBoolean()) {
				apiOk("修改成功");
			}else{
				apiError("修改失败");
			}
		}else{
			apiError(data);
		}
	}

	/**
	 * 洗车用户列表
	 */
	public static void saccUserList(){
		String page = TplPath.saccUserList;
		if (Utils.exitFile(page)){
			renderTemplate(page);
		}
	}

	public static void getSaccUserList() {
		PageBean pageBean = PageBean.get();
		String mobile = params.get("mobile", String.class);
		Long id = params.get("id", Long.class);

		JsonObject data = userDupp.getUserInfoList(id, mobile, pageBean.getOffset(), pageBean.pageCount());
		if (!checkResult(data)) {
			apiError(data);
		}
		List<UserInfoDto> userInfoList = UserInfoDtoUtil.getUserInfoDtoList(data);
		apiList(data, userInfoList);
	}

    public static void editSaccUser() {
        Long id = RequestHelper.getLongParam("id");
        JsonObject saccUser = null;

        if (id > 0) {
            saccUser = userDupp.getSaccUser(id);
        }

        if (saccUser != null) {
            String page = TplPath.editSaccUser;
            if (Utils.exitFile(page)) {
                renderTemplate(page, saccUser);
            }
        }
    }

    public static void saveSaccUser() {
        String mobile = params.get("mobile", String.class);
        Long bindThirdFlag = params.get("bindThirdFlag", Long.class);
        Long bindThirdDb = params.get("bindThirdDb", Long.class);
        Integer washCount = params.get("washCount", Integer.class);
        Integer amountRemain = params.get("amountRemain", Integer.class);
        Integer amountConsume = params.get("amountConsume", Integer.class);
        Long lastStationId = params.get("lastStationId", Long.class);
        Long lastWashTime = params.get("lastWashTime", Long.class);
        Long regeditTime = params.get("regeditTime", Long.class);
        Long id = RequestHelper.getLongParam("id");

        if (id > 0) {
            JsonObject data = userDupp.updateSaccUser(id, mobile, bindThirdFlag, bindThirdDb, washCount, amountRemain, amountConsume, lastStationId, lastWashTime, regeditTime, MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改洗车用户成功");
                } else {
                    apiError("修改洗车用户失败");
                }
            } else {
                apiError(data);
            }
        }
    }

	public static void selectUser(){
		String page = TplPath.selectUser;
		if (Utils.exitFile(page)){
			renderTemplate(page);
		}
	}

}
